'use strict';

const Controller = require('egg').Controller;
// const WXBizDataCrypt = require('../lib/function/WXBizDataCrypt');

const menuRule = {
  shopId: {
    type: 'string',
    required: false,
    allowEmpty: false,
    format: /\d+/
  },
  tableId: {
    type: 'string',
    required: false,
    allowEmpty: false,
    format: /\d+/
  }
};

class IndexController extends Controller {
  async index () {
    const {
      slides,
      imgHost
    } = await this.service.index.index();
    this.ctx.body = {
      slides,
      imgHost
    };
  }
  // 语言
  async language () {
    this.ctx.body = {
      language: {
        shoppingCart: {
          mode: '方式',
          hall: '即用',
          takeout: '预约'
        }
      }
    };
  }

  async menu () {
    this.ctx.validate(menuRule, this.ctx.query);
    const shopId = this.ctx.query.shopId ? this.ctx.query.shopId : 10004;
    const tableId = this.ctx.query.tableId;

    const {
      shop,
      cartTable,
      products,
      productTypes,
      imgHost
    } = await this.service.index.menu(shopId, tableId);

    this.ctx.body = {
      shop,
      cartTable,
      products,
      productTypes,
      imgHost
    };
    // console.log(this.app.api);
    // this.ctx.validate(createRule);
    // const result = await this.app.api.products.get({ filters: { userId: 10021 }, pages: { size: 100 } }); // { idList: [1, 3, 5, 6, 7] }

    // const code = this.ctx.request.body.code;
    // const encryptedData = this.ctx.request.body.encryptedData;
    // const iv = this.ctx.request.body.iv;
    // if (code && encryptedData && iv) {
    //   const result = await this.app.curl('https://api.weixin.qq.com/sns/jscode2session?appid=wxdaef31cd5c76e696&secret=cdb747f73f0b7f8f19340c9ef2821ba2&js_code=' + code + '&grant_type=authorization_code', {
    //     dataType: 'json'
    //   });

    //   console.log(result);

    //   var appId = 'wxdaef31cd5c76e696';
    //   console.log(encryptedData);
    //   console.log(iv);
    //   var pc = new WXBizDataCrypt(appId, result.data.session_key);

    //   var data = pc.decryptData(encryptedData, iv);

    //   const user = await this.app.api.users.signIn(data.unionId, 10021);

    //   console.dir(user);

    //   console.log('解密后 data: ', data);

    //   const avatar = await this.ctx.helper.uploadFile(data.avatarUrl);

    //   const newUser = await this.app.api.users.signUp(data.openId + '1', data.nickName, data.unionId + '1', avatar.body.key, 10021);
    //   console.dir(newUser);
    // }
  }
}

module.exports = IndexController;
